package com.sea.finance.controller;

import com.codecrane.core.controller.UploaderController;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.finance.entity.Inventory;
import com.sea.finance.entity.RefusedTax;
import com.sea.finance.service.InventoryService;
import com.sea.finance.service.RefusedTaxService;
import com.sea.product.service.ChannelService;
import com.sea.supply.service.ProduceService;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *  控制器
 * @author 陈鸿飞
 *  <br/>
 *  <br/>
 */
@Controller
@RequestMapping("/sea/finance/refusedTax")
public class RefusedTaxPayController {

    @Autowired
    private RefusedTaxService refusedTaxService;

    @Autowired
    private ProduceService produceService;


    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        return "/sea/finance/refusedTax/main";
    }


    /**
     * 新增主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage(Model model) {

        model.addAttribute("refusedPo",produceService.findRefusedPo());
        return "/sea/finance/refusedTax/add";
    }

    /**
     * 新增主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(Model model, @RequestParam("id") Integer id) {
        model.addAttribute("refusedTax",refusedTaxService.findById(id));
        return "/sea/finance/refusedTax/edit";
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     RefusedTax refusedTax) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<RefusedTax> list = refusedTaxService.findByCnd(refusedTax);
        PageInfo<RefusedTax> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }




    @RequestMapping("/import")
    @ResponseBody
    public AjaxReturn importClubDo( MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("上传失败！");
        try {
            if (null == file || file.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                UploaderController upload=new UploaderController();
                return upload.uploadFile(file, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
    }


    /**
     * 新增
     * @param refusedTax
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(RefusedTax refusedTax) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != refusedTax && refusedTaxService.save(refusedTax) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 新增
     * @param refusedTax
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(RefusedTax refusedTax) {
        AjaxReturn result = Ajax.fail().setMsg("修改失败！");
        try{
            if (null != refusedTax && refusedTaxService.usave(refusedTax) > 0) {
                result.setOk(true).setMsg("修改成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 新增
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxReturn delete(Integer id) {
        AjaxReturn result = Ajax.fail().setMsg("删除失败！");
        try{
            if (null != id && refusedTaxService.delete(id) > 0) {
                result.setOk(true).setMsg("删除成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 导出收货数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, RefusedTax refusedTax) {
        List<RefusedTax> list = refusedTaxService.findByCnd(refusedTax);
        String[] title = {"海关编号","柜号","实际报关金额",
                          "实际清关金额","报关单附件","清关附件",
                          "退税凭证","退税金额","实际退税","状态","申报年月","退税到账年月"};
        String fileName = "退税信息表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "退税信息表";
        String[][] content = new String[list.size()][12];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            RefusedTax obj = list.get(i);

            content[i][0] = obj.getRefusedNo()+"";
            content[i][1] = obj.getRefusedPlanNo()+"&"+obj.getRefusedNo();
            content[i][2] = obj.getRefusedCreateMoney()+"";
            content[i][3] = obj.getRefusedCustomMoney()+"";
            content[i][4] = obj.getRefusedOrderFile();
            content[i][5] = obj.getRefusedMoneyFile()+"";
            content[i][6] = obj.getRefusedFile()+"";
            content[i][7] = obj.getRefusedMoney()+"";
            content[i][8] = obj.getCreateRefusedTotal()+"";
            if(null==obj.getFlag()  ||  obj.getFlag().equals(0)){
                content[i][9] = "未退税";
            }else{
                content[i][9] = "已退税";
            }
            content[i][10] = obj.getRefusedMonth()+"";
            content[i][11] = obj.getRefusedArriveMonth()+"";
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
